package com.gxgeek.javabasic.nio;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author gaoxing
 * @create 2018-06-04 上午10:44
 */
public class FileChannelTest {
    public static void main(String[] args) {
        String path = "/Users/gaoxing/Desktop/code/study/javastudy";
        String info[] = {"欢迎", "关注", "匠心零度", "的", "公众号", "谢谢！！"};
        File file = new File(path + File.separator + "testfilechannel.txt");
        FileOutputStream output = null;
        FileChannel fout = null;
        try {
            output = new FileOutputStream(file);
            fout = null;
            fout = output.getChannel();
            // 得到输出的通道
            ByteBuffer buf = ByteBuffer.allocate(1024);
            for (int i = 0; i < info.length; i++) {
                buf.put(info[i].getBytes());
                // 字符串变为字节数组放进缓冲区之中
            }
            buf.flip();
                // 输出缓冲区的内容
            fout.write(buf);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fout != null) {
                try {
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
